package cserver.hsk.la.controler;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cserver.hsk.la.data.Message;
import cserver.hsk.la.data.MsgList;

public class MsgServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String res = "";
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");
		String reqMode = req.getParameter("mode");
		PrintWriter writer = resp.getWriter();
		System.out.println("Get " + req.toString());
		if (reqMode.trim().contains("add")) {
			String msg = req.getParameter("msg");
			Message msge = new Message(msg);
			MsgList.Add(msge);
			res = "add_OK";
			System.out.println("Add_OK");
		} else if (reqMode.contains("deleteWithToken")) {
			String deleteToken = req.getParameter("token");
			MsgList.deleteMsgWithToken(deleteToken);
			res = "deleteWithToken_OK";
			System.out.println("deleteWithToken_OK");
		} else if (reqMode.contains("deletewithobject")) {
			String deleteObject = req.getParameter("msg");
			Message msg = new Message(deleteObject);
			MsgList.deleteMsgWithObject(msg);
			res = "deletewithobject_OK";
			System.out.println("deletewithobject_OK");
		} else if (reqMode.contains("getwithtoken")) {

			String token = req.getParameter("token");
			List<Message> msgs = MsgList.getWithToken(token);

			for (int i = 0; i < msgs.size(); i++) {
				res += msgs.get(i).getString();
				if (i != msgs.size() - 1) {
					res += "$.";
				}
			}
			System.out.println("getWithToken_OK");
		} else if (reqMode.contains("deleteall")) {
			MsgList.clearAll();
			res="deleteall";
		} else if (reqMode.contains("showall")) {
			res = MsgList.showAll();
		}
		writer.write(res);
		writer.flush();
		writer.close();

	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

	}

}
